<script setup lang="ts">
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useAppStore } from '../stores/app'

const appStore = useAppStore()
const { jobs } = storeToRefs(appStore)

// 执行历史
const historyPage = ref(1)
const historyPageSize = ref(20)
const historyFilterStatus = ref('')
const historyFilterKeyword = ref('')

// 过滤掉监控任务，只显示预约相关任务
const filteredHistoryJobs = computed(() => {
  let result = jobs.value.filter((job: any) => {
    // 过滤掉监控任务
    if (job?.type === 'monitor')
      return false
    // 只显示预约相关任务
    return job?.type?.startsWith('booking') || !job?.type
  })

  // 状态筛选
  if (historyFilterStatus.value) {
    result = result.filter((job: any) => job.status === historyFilterStatus.value)
  }

  // 关键词搜索
  const kw = (historyFilterKeyword.value || '').trim().toLowerCase()
  if (kw) {
    result = result.filter((job: any) => {
      const res = job?.result || {}
      const ai = res.appointment_info || {}
      const hay = [
        job.job_id,
        res.reference_number,
        ai.user_passport,
        ai.user_name,
        ai.appointment_date,
        ai.office_code,
      ].filter(Boolean).map((v: any) => String(v).toLowerCase()).join(' ')
      return hay.includes(kw)
    })
  }

  return result
})

const paginatedHistoryJobs = computed(() => {
  const start = (historyPage.value - 1) * historyPageSize.value
  const end = start + historyPageSize.value
  return filteredHistoryJobs.value.slice(start, end)
})

// 刷新历史
async function refreshHistory() {
  await appStore.loadJobs()
  ElMessage.success('刷新成功')
}

// 停止历史任务
async function stopHistoryJob(job: any) {
  try {
    if (job?.type && String(job.type).startsWith('booking')) {
      await window.api.booking.stop()
      ElMessage.success('任务已停止')
      await appStore.loadJobs()
    }
    else {
      ElMessage.warning('该任务无法停止')
    }
  }
  catch (error: any) {
    console.error('停止任务失败:', error)
    ElMessage.error('停止任务失败')
  }
}

// 详情弹窗与日志/流量视图（复用 MonitorPage 能力）
const detailVisible = ref(false)
const detailJob = ref<any | null>(null)
function viewJobDetail(job: any) {
  detailJob.value = job
  detailVisible.value = true
}
const detailResult = computed(() => (detailJob.value?.result || {}) as any)
const isBatchJob = computed(() => {
  const t = (detailJob.value as any)?.type
  if (t && String(t).toLowerCase() === 'booking_batch')
    return true
  return Array.isArray((detailResult.value as any)?.appointments)
})
const batchRows = computed(() => {
  if (!isBatchJob.value)
    return [] as Array<any>
  const res = detailResult.value || {}
  const list: Array<any> = Array.isArray(res.appointments) ? res.appointments : []
  const results: Array<any> = Array.isArray(res.results) ? res.results : []
  const byId = new Map<number, any>()
  for (const r of results) byId.set(Number(r?.id), r)
  return list.map((a: any) => {
    const r = byId.get(Number(a?.id)) || {}
    return {
      id: a?.id,
      user_passport: a?.user_passport || '',
      user_name: a?.user_name || '',
      office_code: a?.office_code || '',
      success: !!r?.success,
      error: r?.error || '',
      reference_number: r?.reference_number || '',
      selected_date: r?.selected_date || '',
      selected_timeslot: r?.selected_timeslot || '',
    }
  })
})
const logKeyword = ref('')
const logPhase = ref<'all' | 'start' | 'info' | 'warn' | 'success' | 'error'>('all')
function getPhaseTagType(phase?: string) {
  switch (phase) {
    case 'success': return 'success'
    case 'warn': return 'warning'
    case 'error': return 'danger'
    case 'start': return 'info'
    default: return 'info'
  }
}
const detailLogs = computed(() => {
  const logs = Array.isArray((detailResult.value as any)?.logs) ? (detailResult.value as any).logs : []
  return logs as Array<{ timestamp: number, step?: string, phase?: string, message?: string }>
})
const filteredLogs = computed(() => {
  const kw = (logKeyword.value || '').trim().toLowerCase()
  const ph = logPhase.value
  return detailLogs.value.filter((l) => {
    if (ph !== 'all' && String(l.phase || '').toLowerCase() !== ph)
      return false
    if (!kw)
      return true
    const hay = `${l.step || ''} ${l.message || ''}`.toLowerCase()
    return hay.includes(kw)
  })
})
function formatBytes(n?: number): string {
  const v = Number(n || 0)
  if (v < 1024)
    return `${v} B`
  const kb = v / 1024
  if (kb < 1024)
    return `${kb.toFixed(2)} KB`
  const mb = kb / 1024
  if (mb < 1024)
    return `${mb.toFixed(2)} MB`
  const gb = mb / 1024
  return `${gb.toFixed(2)} GB`
}
const trafficRows = computed(() => {
  const traffic = (detailResult.value as any)?.traffic
  const per = traffic?.perStep || {}
  const rows: Array<{ step: string, up: number, down: number, count: number }> = []
  for (const k of Object.keys(per)) {
    rows.push({ step: k, up: Number(per[k]?.up || 0), down: Number(per[k]?.down || 0), count: Number(per[k]?.count || 0) })
  }
  return rows
})
async function copyLogs() {
  try {
    const lines = filteredLogs.value.map(l => `${new Date((l.timestamp || 0) * 1000).toLocaleString('zh-CN')} [${l.phase || ''}] ${l.step || ''} ${l.message || ''}`)
    await navigator.clipboard.writeText(lines.join('\n'))
    ElMessage.success('日志已复制到剪贴板')
  }
  catch (e) { console.error('复制失败', e); ElMessage.error('复制失败') }
}

// 格式化函数
function formatTime(timestamp?: number | string | Date) {
  if (!timestamp)
    return '-'
  try {
    if (typeof timestamp === 'number') {
      return new Date(timestamp * 1000).toLocaleString('zh-CN')
    }
    if (typeof timestamp === 'string') {
      return new Date(timestamp).toLocaleString('zh-CN')
    }
    return timestamp.toLocaleString('zh-CN')
  }
  catch {
    return '-'
  }
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    pending: '等待中',
    running: '运行中',
    success: '成功',
    failed: '失败',
    cancelled: '已取消',
    processing: '处理中',
    completed: '已完成',
  }
  return map[status] || status
}

function getStatusType(status: string) {
  const map: Record<string, string> = {
    pending: 'info',
    running: 'primary',
    processing: 'primary',
    success: 'success',
    completed: 'success',
    failed: 'danger',
    cancelled: 'warning',
  }
  return map[status] || 'info'
}

// 定时刷新
let refreshTimer: ReturnType<typeof setInterval> | null = null

onMounted(() => {
  appStore.loadJobs()
  refreshTimer = setInterval(() => { appStore.loadJobs() }, 5000)
})

onUnmounted(() => {
  if (refreshTimer)
    clearInterval(refreshTimer)
})
</script>

<template>
  <div class="task-management-page">
    <div class="mb-6">
      <h2 class="mb-2 text-2xl text-gray-800 font-bold">
        预约历史
      </h2>
      <p class="text-gray-600">
        记录每次预约的执行生命周期与结果
      </p>
    </div>

    <div class="card mb-6">
      <div class="flex items-center space-x-2">
        <el-select v-model="historyFilterStatus" size="small" placeholder="状态" style="width: 120px;" clearable>
          <el-option label="全部" value="" />
          <el-option label="运行中" value="running" />
          <el-option label="成功" value="success" />
          <el-option label="失败" value="failed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
        <el-input
          v-model="historyFilterKeyword"
          size="small"
          placeholder="搜索(护照/姓名/参考号)"
          style="width: 260px;"
          clearable
        />
        <el-button size="small" @click="refreshHistory">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <div class="card">
      <el-table :data="paginatedHistoryJobs" stripe border empty-text="暂无执行记录">
        <el-table-column label="任务ID" width="120">
          <template #default="{ row }">
            <code class="text-sm">{{ row.job_id.slice(0, 8) }}...</code>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.progress || 0 }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="当前步骤" min-width="150">
          <template #default="{ row }">
            {{ row.current_step || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="预约信息" min-width="200">
          <template #default="{ row }">
            <div v-if="row?.result?.appointment_info">
              <div class="font-medium">
                {{ row.result.appointment_info.appointment_date || '-' }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.result.appointment_info.appointment_time || '-' }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.result.appointment_info.office_code || '-' }}
              </div>
            </div>
            <div v-else-if="row?.result?.reference_number">
              <div class="font-medium">
                参考号: {{ row.result.reference_number }}
              </div>
              <div class="text-sm text-gray-500">
                {{ row.result.selected_date || '-' }}
              </div>
            </div>
            <div v-else-if="Array.isArray(row?.result?.appointments)">
              <div class="text-sm">
                批次：成功 {{ row.result.success || 0 }}/{{ row.result.total || 0 }}
              </div>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column label="错误信息" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.error" class="text-red-600">{{ row.error }}</span>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewJobDetail(row)">
              详情
            </el-button>
            <el-button
              v-if="row.status === 'running'"
              size="small"
              type="danger"
              @click="stopHistoryJob(row)"
            >
              停止
            </el-button>
            <span v-else class="text-gray-400" />
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="historyPage"
          v-model:page-size="historyPageSize"
          :total="filteredHistoryJobs.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          small
        />
      </div>
    </div>

    <!-- 详情弹窗（带日志/流量/预约信息） -->
    <el-dialog
      v-model="detailVisible"
      title="任务详情"
      width="800px"
    >
      <div class="space-y-4">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">
            <code>{{ detailJob?.job_id }}</code>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(detailJob?.status || 'pending')">
              {{ getStatusText(detailJob?.status || 'pending') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进度">
            {{ `${detailJob?.progress ?? 0}%` }}
          </el-descriptions-item>
          <el-descriptions-item label="当前步骤">
            {{ detailJob?.current_step || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatTime(detailJob?.start_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ formatTime(detailJob?.end_time) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="参考编号">
            {{ (detailResult as any)?.reference_number || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="选择日期">
            {{ (detailResult as any)?.selected_date || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="选择时段">
            {{ (detailResult as any)?.selected_timeslot || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="错误信息">
            {{ detailJob?.error || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="card p-3">
          <h4 class="mb-2 text-base font-semibold">
            流量消耗
          </h4>
          <div class="mb-2 text-sm text-gray-600">
            单位：字节（Byte）
          </div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="总上行">
              {{ formatBytes((detailResult as any)?.traffic?.totalUp) }}
            </el-descriptions-item>
            <el-descriptions-item label="总下行">
              {{ formatBytes((detailResult as any)?.traffic?.totalDown) }}
            </el-descriptions-item>
          </el-descriptions>
          <div class="mt-3">
            <el-table :data="trafficRows" size="small" border>
              <el-table-column label="步骤" prop="step" />
              <el-table-column label="上行" width="160">
                <template #default="{ row }">
                  {{ formatBytes(row.up) }}
                </template>
              </el-table-column>
              <el-table-column label="下行" width="160">
                <template #default="{ row }">
                  {{ formatBytes(row.down) }}
                </template>
              </el-table-column>
              <el-table-column label="请求数" prop="count" width="100" />
            </el-table>
          </div>
        </div>

        <el-descriptions v-if="(detailResult as any)?.appointment_info" :column="2" border class="mt-3">
          <el-descriptions-item label="护照号码">
            {{ (detailResult as any).appointment_info.user_passport || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ (detailResult as any).appointment_info.user_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ (detailResult as any).appointment_info.user_email || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="电话">
            {{ (detailResult as any).appointment_info.user_phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="服务/地点">
            {{ (detailResult as any).appointment_info.service_type || '-' }} / {{ (detailResult as any).appointment_info.office_code || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            {{ (detailResult as any).appointment_info.appointment_date || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ (detailResult as any).appointment_info.appointment_time || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="isBatchJob" class="card mt-3 p-3">
          <h4 class="mb-2 text-base font-semibold">
            预约清单
          </h4>
          <div class="mb-2 text-sm text-gray-600">
            合计：{{ (detailResult as any)?.total || batchRows.length }}；成功：{{ (detailResult as any)?.success || batchRows.filter(r => r.success).length }}；失败：{{ (detailResult as any)?.failed || batchRows.filter(r => !r.success).length }}
          </div>
          <el-table :data="batchRows" size="small" border>
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column label="护照" prop="user_passport" width="140" />
            <el-table-column label="姓名" prop="user_name" width="120" />
            <el-table-column label="地点" prop="office_code" width="120" />
            <el-table-column label="结果" width="100">
              <template #default="{ row }">
                <el-tag :type="row.success ? 'success' : 'danger'">
                  {{ row.success ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="参考号" prop="reference_number" width="160" />
            <el-table-column label="日期" prop="selected_date" width="140" />
            <el-table-column label="时间" prop="selected_timeslot" width="140" />
            <el-table-column label="错误" prop="error" />
          </el-table>
        </div>

        <div>
          <div class="mb-2 flex items-center justify-between">
            <div class="flex items-center space-x-2">
              <el-input v-model="logKeyword" size="small" placeholder="搜索日志关键词（步骤/内容）" style="width: 260px;" />
              <el-select v-model="logPhase" size="small" style="width: 140px;">
                <el-option label="全部" value="all" />
                <el-option label="开始" value="start" />
                <el-option label="信息" value="info" />
                <el-option label="警告" value="warn" />
                <el-option label="成功" value="success" />
                <el-option label="错误" value="error" />
              </el-select>
            </div>
            <div class="flex items-center space-x-2">
              <el-button size="small" @click="copyLogs">
                复制日志
              </el-button>
            </div>
          </div>
          <el-table :data="filteredLogs" height="300" size="small" border>
            <el-table-column label="时间" width="160">
              <template #default="{ row }">
                {{ new Date((row.timestamp || 0) * 1000).toLocaleString('zh-CN') }}
              </template>
            </el-table-column>
            <el-table-column label="级别" width="100">
              <template #default="{ row }">
                <el-tag :type="getPhaseTagType(row.phase)">
                  {{ row.phase || 'info' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="步骤" width="200" prop="step" />
            <el-table-column label="消息" prop="message" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.task-management-page {
  width: 100%;
  max-width: none;
  padding: 0 16px;
  box-sizing: border-box;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (min-width: 1600px) {
  .task-management-page {
    padding: 0 24px;
  }
}
</style>
